layui.use(['form', "fsConfig", "fsCommon", "table"], function () {
    var form = layui.form,
        table = layui.table,
        layer = layui.layer,
        fsConfig = layui.fsConfig,
        fsCommon = layui.fsCommon,
        jumpLogin = $.result(fsConfig, "filters.401");

    var token = localStorage.getItem('cdce_serivce_token');
    if (token === "") {
        jumpLogin()
    }


    function callbackfun(obj) {
        if (obj.times.length == 0) {
            return
        }
        var data = [];
        for (i = 0; i < obj.times.length; i++) {
            data.push({"time": obj.times[i]});
        }
        table.reload("school", {data: data});
    }

    var subject = jQuery.parseJSON(localStorage.getItem('cdce_serivce_subject')),
        school = jQuery.parseJSON(localStorage.getItem('cdce_serivce_school')),
        school_confrim = jQuery.parseJSON(localStorage.getItem('cdce_serivce_school_confrim'));


    fsCommon.get("/participate/v1alpha/" + school.id + "/time/" + subject.id, "", callbackfun);

    table.on('tool(school)', function (obj) {
        var data = obj.data;
        if (obj.event === 'confrim') {
            if (school_confrim == null) {
                school_confrim = []
            }
            school_confrim.push({
                "course_id": subject.id,
                "course": subject.text,
                "school_id": school.id,
                "school": school.school,
                "area": school.area,
                "time": data.time
            });
            localStorage.setItem("cdce_serivce_school_confrim", JSON.stringify(school_confrim));
            unique();
            layer.msg("报名成功", {time: 1000}, function () {
                parent.layer.close(parent.layer.getFrameIndex(window.name));
            });
        }
    });


    function unique() {
        var result = jQuery.parseJSON(localStorage.getItem("cdce_serivce_school_confrim"));
        var obj = {}, data = [];
        for (var i = 0; i < result.length; i++) {
            obj[result[i].course_id + "-" + result[i].school_id] = result[i];
        }
        for (key in obj) {
            data.push(obj[key])
        }
        console.log(data);
        localStorage.setItem("cdce_serivce_school_confrim", JSON.stringify(data));
    }
});